<?php
    require_once "config.php";
    require_once "debug.php";

    function getCached($url)
    {
        //debugMsg($url);

        $pUrl = parse_url($url);

        $domain = $pUrl['host'];
        $path = $pUrl['path'];
        $queryString = @$pUrl['query'];


        //strip of protocol
        $pUrl = $domain.$path.($queryString == "" ? "" : "?".$queryString);

        $targetCacheFile = $GLOBALS['cacheDir'].urlencode($pUrl).".cache";
        debugMsg("Setting target cache file to ".$targetCacheFile);
    
        $cached = "";

        //get filematching pattern
        $cacheConfig = fopen($GLOBALS['cacheConfigFile'], "r");
        $line = "";
        $found = false;
        while (!feof($cacheConfig))
        {
            $line = fgets($cacheConfig);

            if ($line != "")
            {
                $patternAndFile = explode("\t", $line, 2);

                $pattern = trim($patternAndFile[0]);
                $pattern = explode("*",$pattern);
                $pattern = $pattern[0];

                if (substr($pUrl, 0, strlen($pattern)) == $pattern)
                {
                    //found match in cache cfg file
                    $targetCacheFile = $GLOBALS['cacheDir'].trim(substr($line, strlen($pattern)+1));
                    //$targetCacheFile = trim($patternAndFile[1]);
                    debugMsg("Using rules using cache file ". $targetCacheFile." for url ".$pUrl);
                    $found = true;
                    break;
                }
            }
        }

        if (!$found)
        {
            debugMsg("No cache rule found.");
        }
        
        if (file_exists($targetCacheFile))
        {
            debugMsg("returning cached resource: .".$targetCacheFile);
            chmod($targetCacheFile, 0777);
            $response = file_get_contents($targetCacheFile);

            return $response;
        }
        else
        {
            debugMsg("Cachefile ". $targetCacheFile ." not found");
            return "";
        }
    }

    function getCacheFileNameFromUrl($url)
    {
        $pUrl = parse_url($url);

        $domain = $pUrl['host'];
        $path = $pUrl['path'];
        $queryString = @$pUrl['query'];

        $cacheFileName = urlencode($domain.$path.($queryString == "" ? "" : "?".$queryString).".cache");

       return $cacheFileName;
    }

    function addToCache($url, $response)
    {
        $cacheFile = $GLOBALS['cacheDir'].getCacheFileNameFromUrl($url);

        if (!file_exists($cacheFile))
        {
            debugMsg("Adding cached resource ".$cacheFile);
            chmod($cacheFile, 0755);
            $fpc = fopen ($cacheFile, "w");
            fwrite ($fpc, $response);
            fclose ($fpc);
        }
    }
?>